# Python backend stage
FROM python:3.11-slim

# Create non-root user for security
RUN groupadd -r appuser && useradd -r -g appuser appuser

# Set working directory
WORKDIR /app

# Configure faster apt sources for China
RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list.d/debian.sources || \
    sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list

# Install system dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    default-libmysqlclient-dev \
    pkg-config \
    curl \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# Copy backend requirements and install Python dependencies
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

# Copy backend source code
COPY . ./

# Create config file from backup if it doesn't exist
RUN if [ ! -f config.json ] && [ -f config.jsonbak ]; then cp config.jsonbak config.json; fi

# Create a simple default config if none exists
RUN if [ ! -f config.json ]; then \
    echo '{\
      "cors": {\
        "origins": ["*"],\
        "credentials": true,\
        "methods": ["*"],\
        "headers": ["*"]\
      },\
      "api": {\
        "prefix": "/api/v1/mcp",\
        "title": "MCP Server",\
        "version": "1.0.0"\
      },\
      "server": {\
        "host": "0.0.0.0",\
        "port": 8002,\
        "debug": false\
      },\
      "logging": {\
        "level": "info",\
        "backup_count": 7\
      },\
      "database": {\
        "type": "sqlite",\
        "file": "mcp.db"\
      }\
    }' > config.json; \
    fi

# Expose port
EXPOSE 8002

# Change ownership to non-root user
RUN chown -R appuser:appuser /app

# Switch to non-root user
USER appuser

# Add healthcheck
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD curl -f http://localhost:8002/api/v1/mcp/health || exit 1

# Set environment variables
ENV PYTHONPATH=/app
ENV DATABASE_TYPE=sqlite
ENV DATABASE_FILE=mcp.db

# Run the application
CMD ["python", "run.py"]